package tk.mybatis.springboot.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import tk.mybatis.springboot.common.BaseResponse;
import tk.mybatis.springboot.common.ErrorEnum;

/**
 *
 */
@RequestMapping(consumes = "application/json")
public abstract class BaseApiController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${spring.profiles.active}")
    protected String profileActive;

    public BaseResponse success() {
        return success(null);
    }

    public BaseResponse success(Object data) {
        BaseResponse response = BaseResponse.success(ErrorEnum.SUCCESS.getMsg());
        if (data != null) {
            response.setData(data);
        }
        return response;
    }

    public BaseResponse error(ErrorEnum error) {
        return BaseResponse.error(error.getCode(), error.getMsg());
    }

    public BaseResponse error(ErrorEnum error, Object data) {
        return new BaseResponse(false, error.getCode(), error.getMsg(), data);
    }

    public BaseResponse error(int errorCode) {
        return BaseResponse.error(errorCode, ErrorEnum.msg(errorCode));
    }

    public BaseResponse error(int errorCode, String msg) {
        return BaseResponse.error(errorCode, msg);
    }

    public BaseResponse error(ErrorEnum error, Throwable ex) {
        BaseResponse response = error(error);
        if (!isProduct() && ex != null) {
            response.setStackTrace(ExceptionUtils.getStackTrace(ex));
        }
        return response;
    }

    public BaseResponse error(int errorCode, Throwable ex) {
        BaseResponse response = BaseResponse.error(errorCode, ErrorEnum.msg(errorCode));
        if (!isProduct() && ex != null) {
            response.setStackTrace(ExceptionUtils.getStackTrace(ex));
        }
        return response;
    }

    /**
     * 系统环境
     *
     * @return
     */
    public boolean isProduct() {
        if (StringUtils.equals(profileActive, "production")) {
            return true;
        }
        return false;
    }
}
